package org.qingke.mail.sso.service;

import java.text.MessageFormat;
import java.util.Date;

import org.qingke.mail.cache.CacheContext;
import org.qingke.mail.common.Response;
import org.qingke.mail.common.SSORequest;
import org.qingke.mail.domain.TbUser;
import org.qingke.mail.util.JsonUtils;
import org.qingke.mail.util.MD5Util;
import org.qingke.mail.util.ObjectUtil;
import org.qingke.mail.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 单点登录业务实现接口
 * @author Administrator
 *
 */
@Service("ssoService")
public class SSOServiceImpl extends CacheContext implements SSOService{
    
	
	//用户服务基础地址
	@Value("${user.service.url}")
	private String userServiceUrl;
	// 门户首页地址
	@Value("${protal.index}")
	private String protalIndexUrl;
	
	//sso地址
	@Value("${sso.url}")
	private String ssoUrl;
	//业务缓存键
	private String SSO_SERVICE_CACHE_KEY="SSO_SERVICE_CACHE_KEY";
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Override
	public Response check(String propertyName, String propertyValue) {
		// 查询用户服务地址
		String urlTemplate = userServiceUrl +"user/queryByProperty?propertyName={0}&propertyValue={1}";
		
		String queryUrl = MessageFormat.format(urlTemplate, propertyName, propertyValue);
		// 调用用户服务查询属性是否存在
		Response response = restTemplate.getForEntity(queryUrl, Response.class).getBody();
		
		return response;
	}

	@Override
	public Response register(SSORequest userRequest) {
		//如果用户存在
		Response response=check("username", userRequest.getUsername());
		if(response.isState()){
			return response;
		}
		
		response=check("phone", userRequest.getPhone());
		if(response.isState()){
			return response;
		}
		//初始化属性值
		TbUser user=new TbUser();
		user.setCreated(new Date());
		user.setUpdated(new Date());
		user.setEmail(userRequest.getEmail());
		user.setPassword(MD5Util.encryptMD5(userRequest.getPassword()));
		user.setUsername(userRequest.getUsername());
		user.setPhone(userRequest.getPhone());
		
		//调用注册服务接口
		String registerUrl=userServiceUrl+"user/insert";
		response=restTemplate.postForEntity(registerUrl, user, Response.class).getBody();
		return response;
	}

	@Override
	public Response Login(SSORequest userRequest) {
		//如果用户不存在
		Response response=check("username", userRequest.getUsername());
		if(!response.isState()){
			return response;
		}
		// 匹配用户密码
		TbUser user = JsonUtils.jsonToPojo(JsonUtils.objectToJson(response.getData()), TbUser.class);
		if(ObjectUtil.notEmpty(user)&&user.getPassword().equals(MD5Util.encryptMD5(userRequest.getPassword()))){
			 //密码正确
			response.setState(true);
			//生成token
			String token=MD5Util.encryptMD5(user.toString());
			//生成缓存数据
			String data=JsonUtils.objectToJson(user);
			//缓存用户数据
			hSetCache(SSO_SERVICE_CACHE_KEY,token, data);
			//输出token
			response.setToken(token);
			// 如果定向地址为空默认进入门户首页
			if(StringUtil.hasEmpty(userRequest.getRedirectUrl())){
				response.setRedirectUrl(protalIndexUrl);
			}else{
				response.setRedirectUrl(userRequest.getRedirectUrl());
			}
		}else{
			// 登录失败
			response.setState(false);
			response.setMessage("password error");

		}
		return response;
	}
   /**
    * 权限认证
    */
	@Override
	public Response authenication(SSORequest userRequest) {
		Response response=Response.getInstance();
		//认证失败,从缓存中获取token
		Object cacheData=hGetCache(SSO_SERVICE_CACHE_KEY,userRequest.getToken());
		if(ObjectUtil.isEmpty(cacheData)){
			response.setMessage("authenication fail");
			response.setState(false);
			return response;
		}
		
		//认证成功
		response.setData(cacheData);
		response.setMessage("authenication success");
		response.setState(true);
		return response;
	}

}
